class StudentGradeSystem:
    def __init__(self):
        self.students = {}
        
    def add_grade(self):
        while True:
            name = input("请输入学生姓名：")
            if not name:
                print("姓名不能为空！")
                continue
                
            student_id = input("请输入学生学号：")
            if not student_id.isdigit():
                print("学号必须为数字！")
                continue
            if student_id in self.students:
                print("该学号已存在！")
                continue
                
            course = input("请输入课程名称：")
            if not course:
                print("课程名称不能为空！")
                continue
                
            while True:
                grade = input("请输入成绩（0-100）：")
                if not grade.isdigit() or not (0 <= int(grade) <= 100):
                    print("成绩必须为0-100之间的数字！")
                    continue
                break
                
            self.students[student_id] = {
                'name': name,
                'courses': {course: int(grade)}
            }
            print("成绩已成功记录！")
            break
            
    def query_by_name(self):
        name = input("请输入要查询的学生姓名：")
        results = [s for s in self.students.values() if s['name'] == name]
        if not results:
            print("未找到相关记录。")
            return
            
        print("\n===== 查询学生成绩 =====")
        for student in results:
            for course, grade in student['courses'].items():
                print(f"姓名：{student['name']}, 学号：{list(self.students.keys())[list(self.students.values()).index(student)]}, 课程：{course}, 成绩：{grade}.0")
                
    def query_by_id(self):
        student_id = input("请输入要查询的学生学号：")
        student = self.students.get(student_id)
        if not student:
            print("未找到相关记录。")
            return
            
        print(f"\n学生姓名：{student['name']}")
        for course, grade in student['courses'].items():
            print(f"{course}: {grade}分")
            
    def query_by_course(self):
        course = input("请输入要查询的课程名称：")
        results = []
        for student in self.students.values():
            if course in student['courses']:
                results.append((student['name'], student['courses'][course]))
                
        if not results:
            print("未找到相关记录。")
            return
            
        print(f"\n课程：{course}")
        for name, grade in results:
            print(f"{name}: {grade}分")
            
    def course_statistics(self):
        course = input("请输入要统计的课程名称：")
        grades = [s['courses'][course] for s in self.students.values() 
                 if course in s['courses']]
                 
        if not grades:
            print("该课程暂无成绩记录。")
            return
            
        avg = sum(grades) / len(grades)
        max_grade = max(grades)
        min_grade = min(grades)
        
        print("\n===== 统计课程成绩 =====")
        print(f"课程：{course}")
        print(f"平均分：{avg:.2f}")
        print(f"最高分：{max_grade:.1f}")
        print(f"最低分：{min_grade:.1f}")
        
    def show_menu(self):
        print("""
=================================
欢迎使用学生成绩管理系统
=================================
请选择操作：
1. 记录学生成绩
2. 查询学生成绩
3. 统计课程成绩
4. 退出系统
请输入选项序号：""")
        
    def run(self):
        while True:
            self.show_menu()
            choice = input().strip()
            
            if choice == '1':
                self.add_grade()
            elif choice == '2':
                print("""
请选择查询方式：
1. 按姓名查询
2. 按学号查询
3. 按课程查询
请输入选项序号：""")
                query_choice = input().strip()
                if query_choice == '1':
                    self.query_by_name()
                elif query_choice == '2':
                    self.query_by_id()
                elif query_choice == '3':
                    self.query_by_course()
                else:
                    print("无效选项！")
            elif choice == '3':
                self.course_statistics()
            elif choice == '4':
                print("感谢使用学生成绩管理系统，再见！")
                break
            else:
                print("无效选项！")
                
if __name__ == "__main__":
    system = StudentGradeSystem()
    system.run()
